package com.njust.dao;


import com.njust.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.stereotype.Repository;
import java.util.List;


@Repository
public class EmployeeDao {

    public static int employeeId = 1009;

    public static String[] deparments = new String[]{"D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8"};

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 添加员工
     * @param employee
     */
    public boolean saveEmployee(Employee employee){
        String sql = "INSERT INTO emps (last_name, email, gender, department) values (?, ?, ?, ?)";
        int rows = jdbcTemplate.update(sql, employee.getLastName(), employee.getEmail(), employee.getGender(), employee.getDepartment());
        System.out.println("rows = " + rows);
        if (rows <= 0){
            return false;
        }
        return true;
    }

    /**
     * 删除员工
     */
    public boolean deleteEmployee(int id){
        String sql = "DELETE FROM emps WHERE id = ?";
        int rows = jdbcTemplate.update(sql, id);
        System.out.println("rows = " + rows);
        if (rows <= 0){
            return false;
        }
        if (id == employeeId){
            employeeId--;
        }
        return true;
    }

    /**
     * 修改员工
     */
    public boolean updateEmployee(Employee employee){
        String sql = "update emps set last_name = ?, email = ?, gender = ?, department = ? where id = ?";
        int rows = jdbcTemplate.update(sql, employee.getLastName(), employee.getEmail(), employee.getGender(), employee.getDepartment(), employee.getId());
        if (rows <= 0){
            return false;
        }
        return true;
    }

    /**
     * 查找所有员工
     * @return
     */
    public List<Employee> getAllEmployee(){
        String sql = "select * from emps";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        return jdbcTemplate.query(sql, rowMapper);
    }

    /**
     * 根据Id查找员工
     * @return
     */
    public Employee getEmployeeById(int id){
        String sql = "select * from emps where id = ?";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = null;
        try {
            employee = jdbcTemplate.queryForObject(sql, rowMapper, id);
        }catch (DataAccessException e){
            employee = null;
        }
        return employee;
    }
}
